package handler

import (
	"context"
	"github.com/golang/protobuf/ptypes/empty"
	"github.com/golang/protobuf/ptypes/wrappers"
	"github.com/micro/go-micro/util/log"
	"github.com/pku-hit/dict/component/database"
	"github.com/pku-hit/dict/model"
	"github.com/pku-hit/dict/proto"

	"github.com/pku-hit/libresp"
)

type AddressDict struct{}

//获取国家列表
func (e *AddressDict) Countrieslist(ctx context.Context, req *empty.Empty, resp *libresp.ListResponse) error {
	log.Log("Received Dict.GetPatient request")
	dicts, err := database.GetParentlist("0");
	if err != nil {
		resp.GenerateListResponseWithInfo(libresp.GENERAL_ERROR, err.Error())
		return nil
	}
	resp.GenerateListResponseSucc(model.GetDictsAny(dicts))
	return nil
}

//根据parent_id取数据
func (e *AddressDict) GetParentlist(ctx context.Context, req *wrappers.StringValue, resp *libresp.ListResponse) error {
	log.Log("Received Dict.GetPatient request")
	dicts, err := database.GetParentlist(req.Value);
	if err != nil {
		resp.GenerateListResponseWithInfo(libresp.GENERAL_ERROR, err.Error())
		return nil
	}
	resp.GenerateListResponseSucc(model.GetDictsAny(dicts))
	return nil
}
//插入地址数据
func (e *AddressDict) AddaddressDict(ctx context.Context, req *proto.AddaddressDictRequest, resp *libresp.GenericResponse) error {
	log.Log("Received Dict.AddAddaddressDict request")
	dict, err := database.NewaddressDict(req.Category, req.ParentId, req.Code, req.Name, req.PyCode, req.Type, req.Value)
	if err != nil {
		resp.GenerateGenericResponseWithInfo(libresp.GENERAL_ERROR, err.Error())
		return nil
	}
	resp.GenerateGenericResponseSucc(model.GetDictAny(dict))
	return nil
}

func (e *AddressDict) GetAll(ctx context.Context,req *empty.Empty,resp *libresp.ListResponse) error {
	log.Log("Received Dict.GetAll request")
	dicts, err := database.GetParentlist("");
	if err != nil {
		resp.GenerateListResponseWithInfo(libresp.GENERAL_ERROR, err.Error())
		return nil
	}
	resp.GenerateListResponseSucc(model.GetDictsAny(dicts))
	return nil
}
func (e *AddressDict) DeleteAddressDict(ctx context.Context,req *wrappers.StringValue, resp *libresp.Response) error {
	log.Log("Received Dict.DeleteAddressDict request")
	err := database.DeleteAddressDict(req.Value, true)
	if err != nil {
		resp.GenerateResponseWithInfo(libresp.GENERAL_ERROR, err.Error())
	} else {
		resp.GenerateResponseSucc()
	}
	return nil
}